package org.springblade.modules.resource.builder.sms;

import com.aliyuncs.IAcsClient;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.sms.AliSmsTemplate;
import org.springblade.core.sms.model.SmsCode;
import org.springblade.core.sms.model.SmsData;
import org.springblade.core.sms.props.SmsProperties;
import org.springblade.core.tool.utils.StringUtil;

import java.time.Duration;

/**
 * @Description 重写阿里短信模板类（增加短信验证码与手机号码双重认证）
 * @Author ysq
 * @Date 2021/12/20
 **/
public class AliExtSmsTemplate extends AliSmsTemplate {

	private final BladeRedis bladeRedis;

	public AliExtSmsTemplate(SmsProperties smsProperties, IAcsClient acsClient, BladeRedis bladeRedis) {
		super(smsProperties, acsClient, bladeRedis);
		this.bladeRedis = bladeRedis;
	}

	@Override
	public SmsCode sendValidate(SmsData smsData, String phone) {
		SmsCode smsCode = new SmsCode();
		boolean temp = this.sendSingle(smsData, phone);
		if (temp && StringUtil.isNotBlank(smsData.getKey())) {
			String id = StringUtil.randomUUID();
			String value = (String)smsData.getParams().get(smsData.getKey());
			this.bladeRedis.setEx("blade:sms::captcha:" + id + ":" + phone, value, Duration.ofMinutes(30L));
			smsCode.setId(id).setValue(value);
		} else {
			smsCode.setSuccess(Boolean.FALSE);
		}

		return smsCode;
	}

}
